package com.woniuxy.controller;


//增强的WebSocket消息处理器
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.woniuxy.common.entity.ChatMessage;
import com.woniuxy.service.MessageService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ChatHandler extends TextWebSocketHandler {
    @Autowired
    private NotificationHandler notificationHandler; // 注入通知处理器

    @Autowired
    private MessageService MessageService;

    private static final Map<String, WebSocketSession> userSessions = new ConcurrentHashMap<>();
    //创建连接，说明用户打开了聊天界面，把未读的消息发送给用户并把消息标记为已读
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {//对方id,我的id
        String path = session.getUri().getPath();
        String[] parts = path.split("/");
        // 最后两项为 1 和 4
        String receiverId = parts[parts.length - 2]; // 對方用戶id
        String userId = parts[parts.length - 1]; // 當前用戶id
//        String userId = path.substring(path.lastIndexOf('/') + 1);//當前用戶id
        if (userId != null) {
            userSessions.put(userId, session);
            System.out.println("用户连接: " + userId + ", 当前在线: " + userSessions.size());

            // 1. 发送所有未读消息給自己
            boolean b = sendUndeliveredMessages(userId,receiverId);//當前用戶id（收消息的人），對方用戶id（发消息的人）
            if( b==true){
                // 2. 标记消息为已送达
                MessageService.markMessagesAsDelivered(userId,receiverId);
            }
        }
    }
    //发送所有未读消息
    private boolean sendUndeliveredMessages(String userId, String receiverId) {//當前用戶id,對方用戶id
        // 查找两个用户之间的未读消息
        List<ChatMessage> undelivered = MessageService.findByReceiverIdAndStatus(
                userId,receiverId, ChatMessage.MessageStatus.SENT);
        System.out.println("查找未读消息userid: " + userId);
        System.out.println("查找未读消息状态: " + ChatMessage.MessageStatus.SENT);
        if(undelivered != null && undelivered.size() != 0){
            System.out.println("查找未读消息条数: " +undelivered.size());
            for (ChatMessage message : undelivered) {
                System.out.println("发送未读消息: " + message);
//                sendMessageToUser(userId, createMessageJson(message));
            }
            return true;
        }
        return false;

    }

    //创建消息JSON
    private JSONObject createMessageJson(ChatMessage message) {
        JSONObject json = new JSONObject();
        json.put("type", "MESSAGE");
        json.put("id", message.getId());
        json.put("senderId", message.getSenderId());
        json.put("content", message.getContent());
        json.put("timestamp", message.getTimestamp().toString());
        return json;
    }
    //WebSocket连接已经建立，前端调用send方法发送消息时被执行
    @Transactional
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        JSONObject json = JSON.parseObject(message.getPayload());
        String path = session.getUri().getPath();
        String fromUserId = path.substring(path.lastIndexOf('/') + 1);//获取自己的id
//        String fromUserId = (String) session.getAttributes().get("userId");
        String toUserId = json.getString("toUserId");
        String content = json.getString("content");
        System.out.println("toUserId: " + toUserId);
        System.out.println("fromUserId: " + fromUserId);
        System.out.println("content: " + content);

        // 1. 创建并保存消息
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setSenderId(fromUserId);
        chatMessage.setReceiverId(toUserId);
        chatMessage.setContent(content);
        MessageService.save(chatMessage);
        //获取最后一条消息和最后一条消息的时间
        ChatMessage lastMessageObject = MessageService.findLastMessageObject(toUserId, fromUserId);
        String lastcontent = lastMessageObject.getContent();
        LocalDateTime timestamp = lastMessageObject.getTimestamp();
        //获取未读消息数
        Integer unreadCount = MessageService.findUnreadCount(toUserId, fromUserId);

        // 在handleTextMessage方法中，保存消息后添加：
        // 发送新消息通知给接收者
        // 在保存消息后，发送通知

        System.out.println("toUserId:"+toUserId);
        System.out.println("fromUserId:" +fromUserId);
        System.out.println("lastcontent:" + lastcontent);
        System.out.println("timestamp:" +timestamp);
        System.out.println("unreadCount:" +unreadCount);
        // 同时通知发送者（用于多设备同步）
//        notificationHandler.sendNewMessageNotification(fromUserId, fromUserId, lastcontent, timestamp, unreadCount);

        // 2. 尝试发送给接收者
        if (userSessions.containsKey(toUserId)) {
            System.out.println("发送给接收者:" + toUserId);
            // 修复：传递 JSONObject
            sendMessageToUser(toUserId, createMessageJson(chatMessage));
            // 更新消息状态为已送达
            chatMessage.setStatus(ChatMessage.MessageStatus.DELIVERED);
            chatMessage.setDelivered(true);
        }else {
            System.out.println("外面的通知" + toUserId);
            notificationHandler.sendNewMessageNotification(toUserId, fromUserId, lastcontent, timestamp, unreadCount);
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
//        String userId = (String) session.getAttributes().get("userId");
        String path = session.getUri().getPath();
        String userId = path.substring(path.lastIndexOf('/') + 1);//获取自己的id
        System.out.println("用户断开: " + userId);
        if (userId != null) {
            userSessions.remove(userId);
            System.out.println("用户断开: " + userId + ", 剩余在线: " + userSessions.size());
        }
    }


    private void sendMessageToUser(String userId, JSONObject message) {//userID是对方id
        WebSocketSession session = userSessions.get(userId);
        String path = session.getUri().getPath();
        String[] parts = path.split("/");
        String senderId = parts[parts.length - 2]; // 當前用戶id
        if (session != null && session.isOpen()) {
            try {
                // 将 JSONObject 转换为字符串
                session.sendMessage(new TextMessage(message.toJSONString()));
                //修改数据库消息已读
                MessageService.markMessagesAsDelivered(userId,senderId);
                System.out.println("发送了消息了**："+message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("用户 " + userId + " 不在线，消息未送达");
        }
    }
}
